/*
  File: UserRoleMapInterceptor.cs
  Author: rcrxy
  CreateTime: 2025/07/01 16:33

  Description:

  RedisStructure:
    type: Hash
    key:  UserRoleMap
      HashKey:   {UserId}
      HashValue: {RoleId[,]}

*/

using Microsoft.EntityFrameworkCore.Diagnostics;
using StudentVideo.Common.Constants;
using StudentVideo.Data.Entities;
using StudentVideo.Helper;

namespace StudentVideo.Interceptors;

public class UserRoleMapInterceptor(RedisDbHelper redisDb): SaveChangesInterceptor {
   private readonly RedisDbHelper _redisDb = redisDb;

   public override async ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default) {
      var context = eventData.Context;

      await _redisDb.SyncToRedis<UserRoleMapEntity>(context, new() {
         Create = Create,
         Delete = Delete
      });

      return await base.SavedChangesAsync(eventData, result, cancellationToken);
   }

   public async Task Create(UserRoleMapEntity data) {
      // 获取当前用户已有的角色 id 列表
      var roleids = await _redisDb.Db.HashGetAsync(RedisKeys.UserRoleMap, data.UserId);
      HashSet<string> roles = _redisDb.RedisValueToCollection<HashSet<string>, string>(roleids, e => e);

      roles.Add(data.RoleId);
      // 重新写回 redis
      await _redisDb.Db.HashSetAsync(RedisKeys.UserRoleMap, data.UserId, string.Join(',', roles));
   }

   public async Task Delete(UserRoleMapEntity data) {
      var roleids = await _redisDb.Db.HashGetAsync(RedisKeys.UserRoleMap, data.UserId);
      HashSet<string> roles = _redisDb.RedisValueToCollection<HashSet<string>, string>(roleids, e => e);

      if (roles.Any(e => e == data.RoleId)) {
         roles.Remove(data.RoleId);
      }

      await _redisDb.Db.HashSetAsync(RedisKeys.UserRoleMap, data.UserId, string.Join(',', roles));
   }
}
